﻿<#
#=======================================================================================
# Name: ImportDCM.ps1
# Version: 0.1
# Author: Raphael Perez - raphael@rflsystems.co.uk
# Date: 10/01/2013
# Comment: This script will Import all Compliance Settings CI and Baseline from the physical folder
# 
# Updates:
#        0.1 - Raphael Perez - 10/01/2013 - Initial Script
#
# Usage:
#		 Option 1: powershell.exe -ExecutionPolicy Bypass .\ImportDCM.ps1 [Parameters]
#        Option 2: Open Powershell and execute .\ImportDCM.ps1 [Parameters]
#
# Parameters: (All parameters are optional, if you do not use, script will ask you to provide the information)
#        sdkServer - server that will be the sdk server
#        physicalfolder - main folder for the reports, this folder must be the root folder for other folders
#
# Examples:
#        ./ImportDCM.ps1 -sdkServer 'sccm01.mylab.com' -physicalfolder 'c:\customdcm'
#        - connect to the sdk server and discover basic information 
#        - create folder if it does not exist and import all CI and baselines into the correct folder.
#=======================================================================================
#>
PARAM(
    $sdkServer = '',
    $physicalfolder = ''
)
try
{
    $ErrorActionPreference = "Stop"
    $maxretry = 5
    $MediaFolder = $MediaFolder = (Get-Item (Get-Location).Path).Parent.FullName
    if ($MediaFolder -eq '') { (Get-Location).Path }
    if ($mediaFolder.substring($mediaFolder.length-1) -ne '\') { $mediaFolder += '\' }        

    if (!(Test-Path -Path .\Functions.ps1))
    {
        Write-Host "Module Functions.ps1 does not exist on the current folder, no futher action taken" -ForegroundColor Red
    }
    else
    {
        Import-Module -name .\Functions.ps1
    }

    $scriptName = ($MyInvocation.MyCommand.Name)
    $StrDateTime = Get-Date -uformat "%d%m%Y-%H%M"
    $path = $MediaFolder + "_Logs\" + ($MyInvocation.MyCommand.Name -replace '.ps1', '') + ".log"
    $component = ($MyInvocation.MyCommand.Name -replace '.ps1', '')
    New-Item ($MediaFolder + '_Logs') -type directory -force | out-null 
    try
    {
        New-Item ($MediaFolder + '_Logs\Test.log') -type file -force | out-null 
        Remove-Item ($MediaFolder + '_Logs\Test.log') -force | out-null 
    }
    catch
    {
        Write-Host "Unable to read/write file on $MediaFolder folder, no futher action taken" -ForegroundColor Red
        Exit    
    }

    [Environment]::SetEnvironmentVariable("SEE_MASK_NOZONECHECKS", "1", "Process")

    if (!(Test-PowerShell64)) { Exit }
    if (!(Test-IsMediaFolderExist -MediaFolder $MediaFolder)) { Exit }
    $computerinfo = Get-WmiObject Win32_ComputerSystem
    $computerfqdn = $computerinfo.name + '.' + $computerinfo.Domain
    
    if ((gwmi  -namespace 'root\sms' -class 'SMS_ProviderLocation' -ErrorAction SilentlyContinue) -eq $null)
    { $sdkServer = (BuildAnswer -return $sdkServer -Question "SDK Server" -allowblank $false -errorMsg 'SDK Server') }
    else { $sdkserver = (BuildAnswer -return $sdkserver -question 'SDK Server' -default $computerfqdn) }

    $sitecode = (gwmi -namespace 'root\sms' -class 'SMS_ProviderLocation' -ComputerName $sdkserver).SiteCode        
    $physicalfolder = (Get-Folder -return $physicalfolder -Question "DCM Folder (ie: c:\DCM)"  -allowblank $false -errorMsg 'DCM Folder').ToLower()

    Write-Log -Message "sdkServer: $sdkServer"
    Write-Log -Message "sitecode: $sitecode"
    Write-Log -Message "physicalfolder: $physicalfolder"
    
    $folders = get-childitem -path $physicalfolder -Recurse | where-object {$_.PSIsContainer}
    if ($folders -eq $null)
    {
        Write-Log -message "There is no sub-folders under $physicalfolder. No futher action taken" -severity 3
        exit
    }    
    
    $phfolder = ($physicalfolder -replace "\\", "\\") + '\\'
    foreach ($folder in $folders) 
    {   
        $foldername = ($folder.FullName -replace $phfolder, "") -replace '\\', '/'
        Add-CMFolder -sdkServer $sdkServer -sitecode $siteCode -FolderName $foldername -FolderType 2011 | Out-Null
        Add-CMFolder -sdkServer $sdkServer -sitecode $siteCode -FolderName $foldername -FolderType 6001 | Out-Null
        
        $xmlfiles = get-childitem -path $folder.FullName -Filter *.xml
        foreach ($xmlfile in $xmlfiles)
        {
            $resfile = get-childitem -path $folder.FullName -Filter ($xmlfile.name -replace '.xml', '*.resx')
            if ($resfile -ne $null)
            { Import-DCMXml $sdkServer -sitecode $siteCode -xmlfilePath $xmlfile.FullName -resxfilePath $resfile[0].FullName -folder $foldername}
            else { Write-Log -message "Ignoring file $($xmlfile.FullName) as there is no resource file associated" -severity 2 }
        }
    }

    [Environment]::SetEnvironmentVariable("SEE_MASK_NOZONECHECKS", "0", "Process")

    Write-Log -Message "Execution of $scriptName terminated"
}
finally
{
    $module = Get-Module -name Functions | where-object {$_.ModuleType -eq "Script"}
    if ($module -ne $null) 
    { 
        if ($module.Path.ToLower() -eq ($MediaFolder.ToLower() + "scripts\functions.ps1")) { Remove-Module $module }
    }
}